"use client";

import { useState, useRef, KeyboardEvent, useEffect } from 'react';
import { VoiceRecorder } from './VoiceRecorder';

interface MessageComposerProps {
  onSendMessage: (content: string) => Promise<any>;
  disabled?: boolean;
  placeholder?: string;
  className?: string;
  autoFocus?: boolean;
  sending?: boolean;
}

export function MessageComposer({ 
  onSendMessage, 
  disabled = false, 
  placeholder = "Type a message...",
  className = "",
  autoFocus = true,
  sending = false
}: MessageComposerProps) {
  const [content, setContent] = useState('');
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  // Auto focus
  useEffect(() => {
    if (autoFocus && textareaRef.current && !disabled) {
      textareaRef.current.focus();
    }
  }, [autoFocus, disabled]);

  // Keep focus after sending
  const focusTextarea = () => {
    if (textareaRef.current && !disabled) {
      textareaRef.current.focus();
    }
  };

  const handleSend = async () => {
    if (!content.trim() || sending || disabled) return;

    try {
      await onSendMessage(content.trim());
      setContent('');
      // Reset textarea height
      if (textareaRef.current) {
        textareaRef.current.style.height = 'auto';
      }
      // Refocus after sending
      setTimeout(() => {
        focusTextarea();
      }, 100);
    } catch (error) {
      console.error('Failed to send message:', error);
    }
  };

  const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  const handleVoiceTranscription = (text: string) => {
    setContent(text);
    // Auto send speech-to-text result
    if (text.trim()) {
      handleSend();
    }
  };

  const handleInput = () => {
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
      textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
    }
  };

  return (
    <div className={`p-4 ${className}`}>
      <div className="flex items-end gap-3">
        <div className="flex-1 min-w-0">
          <textarea
            ref={textareaRef}
            value={content}
            onChange={(e) => {
              setContent(e.target.value);
              handleInput();
            }}
            onKeyDown={handleKeyDown}
            placeholder={placeholder}
            disabled={disabled || sending}
            className="w-full resize-none rounded-2xl border theme-border px-4 py-3 text-sm theme-text-primary placeholder-theme-text-secondary focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20 disabled:bg-gray-50 disabled:text-gray-500 transition-all shadow-sm theme-bg-primary"
            rows={1}
            style={{ minHeight: '44px', maxHeight: '120px' }}
          />
        </div>

        <VoiceRecorder
          onTranscription={handleVoiceTranscription}
          disabled={disabled || sending}
        />

        <button
          onClick={handleSend}
          disabled={!content.trim() || sending || disabled}
          className="rounded-2xl bg-gradient-to-r from-blue-500 to-blue-600 px-6 py-3 text-sm font-medium text-white hover:from-blue-600 hover:to-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:ring-offset-2 disabled:from-gray-300 disabled:to-gray-300 disabled:cursor-not-allowed transition-all shadow-sm flex-shrink-0 min-w-[80px]"
        >
          {sending ? (
            <div className="flex items-center gap-2">
              <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
              <span className="hidden sm:inline">Sending...</span>
            </div>
          ) : (
            <span>Send</span>
          )}
        </button>
      </div>
      <div className="mt-3 text-xs theme-text-secondary">
        <div className="hidden sm:flex sm:items-center sm:gap-4">
          <span>Press Enter to send, Shift + Enter for new line</span>
          <div className="flex items-center gap-1">
            <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11a7 7 0 01-7 7v1a1 1 0 01-1 1h-2a1 1 0 01-1-1v-1a7 7 0 01-7-7V7a1 1 0 011-1h2a1 1 0 011 1v4a5 5 0 005 5h0a5 5 0 005-5V7a1 1 0 011-1h2a1 1 0 011 1v4z" />
            </svg>
            <span>Supports voice input</span>
          </div>
        </div>
      </div>
    </div>
  );
}